#!/usr/bin/env python
"""
数据库迁移管理脚本
使用方法:
    python migrate.py init      # 初始化迁移环境
    python migrate.py migrate   # 创建迁移文件
    python migrate.py upgrade   # 应用迁移
    python migrate.py downgrade # 回滚迁移
"""
import sys
import os

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from flask_migrate import init, migrate, upgrade, downgrade
from app import create_app, db

def main():
    """主函数"""
    if len(sys.argv) < 2:
        print("使用方法: python migrate.py [init|migrate|upgrade|downgrade]")
        return
    
    command = sys.argv[1]
    app = create_app()
    
    with app.app_context():
        if command == 'init':
            print("初始化迁移环境...")
            init()
            print("迁移环境初始化完成!")
            
        elif command == 'migrate':
            message = sys.argv[2] if len(sys.argv) > 2 else "auto migration"
            print(f"创建迁移文件: {message}")
            migrate(message=message)
            print("迁移文件创建完成!")
            
        elif command == 'upgrade':
            print("应用迁移...")
            upgrade()
            print("迁移应用完成!")
            
        elif command == 'downgrade':
            revision = sys.argv[2] if len(sys.argv) > 2 else '-1'
            print(f"回滚迁移到: {revision}")
            downgrade(revision=revision)
            print("迁移回滚完成!")
            
        else:
            print(f"未知命令: {command}")
            print("可用命令: init, migrate, upgrade, downgrade")

if __name__ == '__main__':
    main()